<template>
  <div class="snow-page">
    <a-card title="企业添加" style="width: 99%" hoverable>
      <template #extra>
        <a-button size="mini" type="primary" @click="goBack">返回</a-button>
      </template>
      <div class="">
        <div class="snow-inner-page">
          <a-row :gutter="24">
            <a-form ref="formRef" :size="form.size" :model="form" auto-label-width @submit="handleSubmit">
              <div style="display: flex">
                <a-col :span="12">
                  <a-form-item field="cq_parent_code" label="父级企业编码" :rules="[{ required: true, message: '父级企业编码不能为空' }]"
                    :validate-trigger="['change', 'input']">
                    <a-tree-select v-model="form.cq_parent_code" :field-names="filrname" :data="treeNodes"
                      placeholder="父级企业编码" allow-clear></a-tree-select>
                  </a-form-item>
                  <a-form-item field="name" label="企业名称" :rules="[{ required: true, message: '企业名称不能为空' }]"
                    :validate-trigger="['change', 'input']">
                    <a-input v-model="form.name" placeholder="请输入企业名称" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_nrcc_code" label="化学品登记系统编码">
                    <a-input v-model="form.cq_nrcc_code" placeholder="化学品登记系统编码" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_company_short_name" label="企业简称">
                    <a-input v-model="form.cq_company_short_name" placeholder="请输入企业简称" allow-clear />
                  </a-form-item>

                  <a-form-item field="cq_company_code" label="企业编码" :rules="[{ required: true, message: '企业编码不能为空' }]">
                    <a-input v-model="form.cq_company_code" placeholder="企业编码" allow-clear :disabled="editDisabled" />
                  </a-form-item>
                  <a-form-item field="cq_address_registry" label="工商注册地址"
                    :rules="[{ required: true, message: '工商注册地址不能为空' }]">
                    <a-input v-model="form.cq_address_registry" placeholder="请输入工商注册地址" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_address_worksite" label="生产场地地址"
                    :rules="[{ required: true, message: '生产场地地址不能为空' }]">
                    <a-input v-model="form.cq_address_worksite" placeholder="请输入生产场地地址" allow-clear>
                    </a-input>
                  </a-form-item>
                  <a-form-item field="lon" label="经度"
                    :rules="[{ required: true, message: '经度不能为空' }]">
                    <a-input v-model="form.lon" placeholder="请输入经度" allow-clear>
                    </a-input>
                  </a-form-item>
                  <a-form-item field="lat" label="纬度"
                    :rules="[{ required: true, message: '纬度不能为空' }]">
                    <a-input v-model="form.lat" placeholder="请输入纬度" allow-clear>
                    </a-input>
                  </a-form-item>
                  <a-form-item field="cq_area_code" label="行政区域编码" :rules="[{ required: true, message: '地区不能为空' }]">
                    <a-cascader :options="regionData" v-model="form.cq_area_code" placeholder="请选择地区" allow-clear allow-search/>
                  </a-form-item>

                  <a-form-item field="cq_representative_person" label="法定代表人"
                    :rules="[{ required: true, message: '法定代表人不能为空' }]">
                    <a-input v-model="form.cq_representative_person" placeholder="请输入法定代表人" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_responsible_person" label="企业负责人"
                    :rules="[{ required: true, message: '企业负责人不能为空' }]">
                    <a-input v-model="form.cq_responsible_person" placeholder="请输入企业负责人" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_responsible_mobile" label="企业负责人手机">
                    <a-input v-model="form.cq_responsible_mobile" placeholder="请输入企业负责人手机" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_responsible_phone" label="企业负责人电话">
                    <a-input v-model="form.cq_responsible_phone" placeholder="请输入企业负责人电话" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_safety_responsible_person" label="安全负责人"
                    :rules="[{ required: true, message: '安全负责人不能为空' }]">
                    <a-input v-model="form.cq_safety_responsible_person" placeholder="请输入安全负责人" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_safety_responsible_mobile" label="安全负责人手机"
                    :rules="[{ required: true, message: '安全负责人手机不能为空' }]">
                    <a-input v-model="form.cq_safety_responsible_mobile" placeholder="请输入安全负责人电话" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_safety_responsible_phone" label="安全负责人电话">
                    <a-input v-model="form.cq_safety_responsible_phone" placeholder="请输入安全负责人电话" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_safety_standard_grad" label="安全生产标准化等级">
                    <a-select v-model="form.cq_safety_standard_grad" placeholder="安全生产标准化等级" allow-clear>
                      <a-option v-for="(item, index) in optinos500" :key="index" :value="item.id">{{ item.name
                        }}</a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item field="cq_safety_license_no" label="安全生产许可证编号">
                    <a-input v-model="form.cq_safety_license_no" placeholder="安全生产许可证编号" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_safety_license_start" label="安全生产许可证有效期开始日期">
                    <a-date-picker v-model="form.cq_safety_license_start" placeholder="安全生产许可证有效期开始日期" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_safety_license_end" label="安全生产许可证有效期结束日期">
                    <a-date-picker v-model="form.cq_safety_license_end" placeholder="安全生产许可证有效期结束日期" allow-clear />
                  </a-form-item>

                </a-col>
                <a-col :span="12">
                  <a-form-item field="cq_duty_phone" label="安全值班电话" :rules="[{ required: true, message: '安全值班电话不能为空' }]"
                    :validate-trigger="['change', 'input']">
                    <a-input v-model="form.cq_duty_phone" placeholder="请输入安全值班电话" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_post_code" label="邮政编码">
                    <a-input v-model="form.cq_post_code" placeholder="请输入邮政编码" allow-clear />
                  </a-form-item>

                  <a-form-item field="cq_web_site" label="网址">
                    <a-input v-model="form.cq_web_site" placeholder="请输入网址" allow-clear />
                  </a-form-item>
                  <a-form-item field="description" label="描述">
                    <a-textarea v-model="form.description" placeholder="请输入描述" allow-clear />
                  </a-form-item>

                  <a-form-item field="cq_establish_date" label="成立日期">
                    <a-date-picker v-model="form.cq_establish_date" placeholder="请选择成立日期" allow-clear />
                  </a-form-item>

                  <a-form-item field="cq_company_scale" label="企业规模" :rules="[{ required: true, message: '企业规模不能为空' }]">
                    <a-select v-model="form.cq_company_scale" placeholder="请输入企业规模" allow-clear>
                      <a-option v-for="(item, index) in optinos387" :key="index" :value="item.id">{{ item.name
                        }}</a-option>
                    </a-select>
                  </a-form-item>

                  <a-form-item field="cq_company_type" label="企业类型" :rules="[{ required: true, message: '企业类型不能为空' }]">
                    <a-select v-model="form.cq_company_type" placeholder="请输入企业类型" allow-clear>
                      <a-option v-for="(item, index) in optinos392" :key="index" :value="item.id">{{ item.name
                        }}</a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item field="cq_economic_type" label="经济类型" :rules="[{ required: true, message: '经济类型不能为空' }]">
                    <a-select v-model="form.cq_economic_type" placeholder="请输入经济类型" allow-clear>
                      <a-option v-for="(item, index) in optinos396" :key="index" :value="item.id">{{ item.name
                        }}</a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item field="cq_industry_category" label="所属行业门类"
                    :rules="[{ required: true, message: '所属行业门类不能为空' }]">
                    <a-select v-model="form.cq_industry_category" @change="changeCateGory" placeholder="请输入所属行业门类"
                      allow-clear allow-search>
                      <a-option v-for="item in optinos431" :key="item.id" :value="item.id" :label="item.name">{{
                        item.name
                        }}</a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item field="cq_industry_class" label="所属行业大类"
                    :rules="[{ required: true, message: '所属行业大类不能为空' }]">
                    <a-select v-model="form.cq_industry_class" placeholder="请输入所属行业大类" allow-clear allow-search>
                      <a-option v-for="item in optinos431_1" :key="item.id" :value="item.id" :label="item.name">{{
                        item.name
                        }}</a-option>
                    </a-select>
                  </a-form-item>
                  <a-form-item field="cq_social_credit_code" label="统一社会信用代码">
                    <a-input v-model="form.cq_social_credit_code" placeholder="统一社会信用代码" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_business_scope" label="营业执照经营范围">
                    <a-input v-model="form.cq_business_scope" placeholder="营业执照经营范围" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_in_industrial_park" label="是否在化工园区内">
                    <a-radio-group v-model="form.cq_in_industrial_park" placeholder="是否在化工园区内" allow-clear>
                      <a-radio value="1">是</a-radio>
                      <a-radio value="0">否</a-radio>
                    </a-radio-group>
                  </a-form-item>
                  <a-form-item field="cq_industrial_park_name" label="所属化工园区名称">
                    <a-input v-model="form.cq_industrial_park_name" placeholder="所属化工园区名称" allow-clear />
                  </a-form-item>
                  <a-form-item field="cq_people_hazard" label="危险化学品作业人员人数">
                    <a-input-number v-model="form.cq_people_hazard" placeholder="危险化学品作业人员人数" allow-clear :min="0" />
                  </a-form-item>
                  <a-form-item field="cq_people_operation" label="特种作业人员人数">
                    <a-input-number v-model="form.cq_people_operation" placeholder="特种作业人员人数" allow-clear :min="0" />
                  </a-form-item>
                  <a-form-item field="cq_people_employee" label="职工人数">
                    <a-input-number v-model="form.cq_people_employee" placeholder="职工人数" allow-clear :min="0" />
                  </a-form-item>
                  <a-form-item field="cq_people_practitioner" label="从业人员人数">
                    <a-input-number v-model="form.cq_people_practitioner" placeholder="从业人员人数" allow-clear :min="0" />
                  </a-form-item>
                  <a-form-item field="cq_people_toxic" label="剧毒化学品作业人员人数">
                    <a-input-number v-model="form.cq_people_toxic" placeholder="剧毒化学品作业人员人数" allow-clear :min="0" />
                  </a-form-item>
                  <!-- /cq_social_credit_code -->
                </a-col>
              </div>
              <div style="text-align: center; margin-left: 35%">
                <a-form-item>
                  <a-space>
                    <a-button type="primary" html-type="submit">提交</a-button>
                    <a-button @click="onReset">重置</a-button>
                  </a-space>
                </a-form-item>
              </div>
            </a-form>
          </a-row>
        </div>
      </div>

      <a-modal v-model:visible="mapopen" title="选择位置" width="50%">
        <div id="mapContainer" style="width: 100%; height: 400px"></div>
        <div class="input-container">
          <input v-model="longitude" @keyup.enter="locatePosition" placeholder="输入经度" class="coordinate-input" />
          <input v-model="latitude" @keyup.enter="locatePosition" placeholder="输入纬度" class="coordinate-input" />
          <button @click="locatePosition" class="locate-button">定位</button>
        </div>
      </a-modal>
    </a-card>
  </div>
</template>


<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import { ref, reactive, onMounted } from "vue";
import { regionData } from "element-china-area-data";
import { getAllqiyeAPI, updatelqiyeAPI, addqiyeAPI } from "@/api/modules/qiye/index";
import { getDictBycodeAPI, getDictBycode3API } from "@/api/modules/dictionary/index";
import axios from "axios";
const router = useRouter();
onMounted(() => {
  getInit();

  getDictBycodeAPIFun();
  getDictBycodeAPIFun2();
  getDictBycodeAPIFun3();
  getDictBycodeAPIFun4();
  getDictBycodeAPIFun6();

  getFuzhi();
});

const editDisabled = ref(false)

function getFuzhi() {
  let userInfo = JSON.parse(localStorage.getItem("user-info") as string);
  editDisabled.value = true
  form.cq_parent_code = userInfo.sharedObject.cq_parent_code;
  form.name = userInfo.sharedObject.name;
  form.cq_nrcc_code = userInfo.sharedObject.cq_nrcc_code;
  form.cq_company_short_name = userInfo.sharedObject.cq_company_short_name;
  form.cq_company_code = userInfo.sharedObject.cq_company_code;
  form.cq_address_registry = userInfo.sharedObject.cq_address_registry;
  form.cq_address_worksite = userInfo.sharedObject.cq_address_worksite;
  form.cq_area_code = userInfo.sharedObject.cq_area_code ? userInfo.sharedObject.cq_area_code : undefined;
  form.cq_representative_person = userInfo.sharedObject.cq_representative_person;
  form.cq_responsible_person = userInfo.sharedObject.cq_responsible_person;
  form.cq_responsible_phone = userInfo.sharedObject.cq_responsible_phone;
  form.cq_safety_responsible_person = userInfo.sharedObject.cq_safety_responsible_person;
  form.cq_safety_responsible_mobile = userInfo.sharedObject.cq_safety_responsible_mobile;
  form.cq_safety_responsible_phone = userInfo.sharedObject.cq_safety_responsible_phone;
  form.cq_safety_standard_grad = userInfo.sharedObject.cq_safety_standard_grad
    ? parseInt(userInfo.sharedObject.cq_safety_standard_grad)
    : undefined;
  form.cq_safety_license_no = userInfo.sharedObject.cq_safety_license_no;
  form.cq_safety_license_start = userInfo.sharedObject.cq_safety_license_start;
  form.cq_safety_license_end = userInfo.sharedObject.cq_safety_license_end;
  form.cq_people_employee = userInfo.sharedObject.cq_people_employee;
  form.cq_people_practitioner = userInfo.sharedObject.cq_people_practitioner;
  form.cq_people_toxic = userInfo.sharedObject.cq_people_toxic;
  form.cq_duty_phone = userInfo.sharedObject.cq_duty_phone;
  form.cq_post_code = userInfo.sharedObject.cq_post_code;
  form.cq_web_site = userInfo.sharedObject.cq_web_site;
  form.description = userInfo.sharedObject.description;
  form.lon = userInfo.sharedObject.lon;
  form.lat = userInfo.sharedObject.lat;
  form.cq_establish_date = userInfo.sharedObject.cq_establish_date;
  form.cq_company_scale = userInfo.sharedObject.cq_company_scale ? parseInt(userInfo.sharedObject.cq_company_scale) : undefined;
  form.cq_company_type = userInfo.sharedObject.cq_company_type ? parseInt(userInfo.sharedObject.cq_company_type) : undefined;
  form.cq_economic_type = userInfo.sharedObject.cq_economic_type ? parseInt(userInfo.sharedObject.cq_economic_type) : undefined;
  form.cq_industry_category = userInfo.sharedObject.cq_industry_category
    ? parseInt(userInfo.sharedObject.cq_industry_category)
    : undefined;

  form.cq_social_credit_code = userInfo.sharedObject.cq_social_credit_code;
  form.cq_business_scope = userInfo.sharedObject.cq_business_scope;
  if(userInfo.sharedObject.cq_in_industrial_park=="1" || userInfo.sharedObject.cq_in_industrial_park=="0"){
    form.cq_in_industrial_park = (userInfo.sharedObject.cq_in_industrial_park)+"";
  }
 
  form.cq_industrial_park_name = userInfo.sharedObject.cq_industrial_park_name;
  form.cq_people_hazard = userInfo.sharedObject.cq_people_hazard;
  form.cq_people_operation = userInfo.sharedObject.cq_people_operation;
  form.id = userInfo.sharedObject.id;
}

const treeNodes = ref([]);

async function getInit() {
  let obj = {};

  let res = await getAllqiyeAPI(obj);

  if (res.status == 2) {
    treeNodes.value = generateTreeNodes(res.data);

  }
}

const optinos387 = ref([]);

async function getDictBycodeAPIFun() {
  let res = await getDictBycodeAPI(387);
  if (res.status == 2) {
    optinos387.value = res.data;
  }
}
const optinos392 = ref([]);
async function getDictBycodeAPIFun2() {
  let res = await getDictBycodeAPI(392);
  if (res.status == 2) {
    optinos392.value = res.data;
  }
}

const optinos396 = ref([]);
async function getDictBycodeAPIFun3() {
  let res = await getDictBycodeAPI(396);
  if (res.status == 2) {
    optinos396.value = res.data;
  }
}

const optinos500 = ref([]);
async function getDictBycodeAPIFun6() {
  let res = await getDictBycodeAPI(500);
  if (res.status == 2) {
    optinos500.value = res.data;
  }
}

const optinos431 = ref([]);
function getDictBycodeAPIFun4() {
  getDictBycodeAPI(431).then(res => {
    if (res.status == 2) {
      optinos431.value = res.data;
      let obj = optinos431.value.filter(e => {
        return e.id == form.cq_industry_category;
      });
      if (obj.length > 0) {
        getDictBycodeAPIFun5(obj[0].code);
      }

      let userInfo = JSON.parse(localStorage.getItem("user-info") as string);
      if (userInfo) {
        form.cq_industry_class = userInfo.sharedObject.cq_industry_class
          ? parseInt(userInfo.sharedObject.cq_industry_class)
          : undefined;
      }
    }
  });
}

const optinos431_1 = ref([]);

function changeCateGory(val) {
  console.log(val);
  let obj = optinos431.value.filter(e => {
    return e.id == val;
  });
  getDictBycodeAPIFun5(obj[0].code);
}

async function getDictBycodeAPIFun5(code) {
  let paged = 1;
  let pageSize = 100;
  let obj = {
    p_code: code
  };
  let res = await getDictBycode3API(paged, pageSize, obj);
  if (res.status == 2) {
    optinos431_1.value = res.data.data;
  }
}

const filrname = ref({
  key: "id",
  value: "id",
  title: "name",
  children: "children"
});

function generateTreeNodes(data) {
  const nodeMap = new Map();
  const rootNodes = [
    {
      id: "0",
      name: "根节点",
      children: []
    }
  ];

  // First pass: create nodes and store them in a map
  data.forEach(item => {
    const node = {
      id: item.cq_company_code,
      name: item.name,
      children: [],
      data: item // Store all original data
    };
    nodeMap.set(item.cq_company_code, node);
  });

  // Second pass: build the tree structure
  data.forEach(item => {
    const node = nodeMap.get(item.cq_company_code);
    if (item.cq_parent_code === "0") {
      rootNodes[0].children.push(node);
    } else {
      const parentNode = nodeMap.get(item.cq_parent_code);
      if (parentNode) {
        parentNode.children.push(node);
      } else {
        console.warn(`Parent node ${item.cq_parent_code} not found for ${item.cq_company_code}`);
        rootNodes[0].children.push(node); // Add to root if parent not found
      }
    }
  });

  return rootNodes;
}



const handleSubmit = async ({ values, errors }) => {

  if (errors) {
    return;
  }
  values.cq_parent_code = values.cq_parent_code != "0" ? values.cq_parent_code : "0";
  let res: any = "";
  if (form.id) {
    res = (await updatelqiyeAPI(values)) as any;
  } else {
    res = (await addqiyeAPI(values)) as any;
  }

  if (res.status == 2) {
    // router.back();
    Message.success("操作成功");
  } else {
    Message.error(res.statusMsg);
  }
  console.log("values:", values, "\nerrors:", errors);
};



const mapopen = ref(false);

// 将序列化的字符串美观输出，\t 换行

const form = reactive({

}) as any;

const formRef = ref();
const onReset = () => {
  formRef.value.resetFields();
};

function goBack() {
  router.back();
}

// function onSearch() {

// mapopen.value = true;

// setTimeout(function () {
//   initMap();
// }, 500);
// }
const longitude = ref("");
const latitude = ref("");
const map = ref({}) as any;
let marker: any;

const locatePosition = () => {
  const lon = parseFloat(longitude.value);
  const lat = parseFloat(latitude.value);
  form.lon = lon;
  form.lat = lat;
  if (isNaN(lon) || isNaN(lat)) {
    alert("请输入有效的经纬度");
    return;
  }

  const lnglat = new window.T.LngLat(lon, lat);

  // 移动地图中心
  map.value.panTo(lnglat);

  // 清除现有标记
  map.value.clearOverLays();

  // 添加新标记
  marker = new window.T.Marker(lnglat);
  map.value.addOverLay(marker);

  // 设置缩放级别
  map.value.setZoom(13);

  getAddressInfo();
};

function initMap() {
  //map创建地图实例

  map.value = new T.Map(document.getElementById("mapContainer"));

  // 设置地图中心点和缩放级别
  map.value.centerAndZoom(new T.LngLat(121.42638, 31.63153), 11);

  map.value.on("click", function (e) {
    map.value.clearOverLays();
    console.log(e);
    form.lon = e.lnglat.lng;
    form.lat = e.lnglat.lat;
    longitude.value = e.lnglat.lng;
    latitude.value = e.lnglat.lat;
    getAddressInfo();
    const position = new T.LngLat(e.lnglat.lng, e.lnglat.lat);
    let icon = new T.Icon({
      iconUrl: "./icon.png", // 请求图标图片的URL
      iconSize: new T.Point(40, 40), // 图标可视区域的大小
      iconAnchor: new T.Point(30, 30) // 图标的定位锚点
    });
    const marker = new T.Marker(position, { icon: icon });
    map.value.addOverLay(marker);
  });
}

async function getAddressInfo() {
  let Tokens = "20f5dad7c9e6207216d4d7d971fbed3f";
  let postStr = {
    lon: form.lon,
    lat: form.lat,
    ver: 1
  };
  let url = "https://api.tianditu.gov.cn/geocoder";
  // Lambda写法
  let res = await axios({
    method: "get",
    url: url,
    params: {
      postStr: JSON.stringify(postStr),
      type: "geocode",
      tk: Tokens
    },
    timeout: 1000
  });
  // 响应成功回调
  if (res.data.msg == "ok") {
    form.cq_address_worksite = res.data.result.formatted_address;
  }
}
</script>

<style lang="scss">
.arco-input-wrapper .arco-input[disabled] {
  -webkit-text-fill-color: #8f7e7e !important;
}

// .arco-form-item {
//   margin-bottom: 10px !important;
// }
.arco-input-wrapper.arco-input-disabled .arco-input-prefix,
.arco-input-wrapper.arco-input-disabled .arco-input-suffix {
  color: #000 !important;
}

.input-container {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1000;
  display: flex;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 10px;
  border-radius: 4px;
}

.coordinate-input {
  padding: 8px;
  font-size: 14px;
  border: 1px solid #ccc;
  border-radius: 4px;
  width: 120px;
  margin-right: 5px;
}

.locate-button {
  padding: 8px 16px;
  font-size: 14px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.locate-button:hover {
  background-color: #45a049;
}
</style>
